package team.knowers.qzh.qzhserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import team.knowers.qzh.qzhserver.dao.entity.UserSubjectDO;
import team.knowers.qzh.qzhserver.dao.mapper.UserSubjectMapper;
import team.knowers.qzh.qzhserver.dto.req.SetAsMySubjectReqDTO;
import team.knowers.qzh.qzhserver.service.MySubjectService;

/**
 * @author xtg
 */
@Service
public class MySubjectServiceImpl extends ServiceImpl<UserSubjectMapper, UserSubjectDO> implements MySubjectService {
    @Override
    public Boolean setSubjectAsMySubject(SetAsMySubjectReqDTO reqDTO) {
        LambdaQueryWrapper<UserSubjectDO> eq = Wrappers.lambdaQuery(UserSubjectDO.class).eq(UserSubjectDO::getDelFlag, 0).eq(UserSubjectDO::getUsername, reqDTO.getUsername());
        UserSubjectDO userSubjectDO = baseMapper.selectOne(eq);
        UserSubjectDO one = new UserSubjectDO();
        one.setUsername(reqDTO.getUsername());
        one.setDelFlag(0);
        one.setSubjectId(reqDTO.getSubjectId());
        if (userSubjectDO != null) {
            LambdaUpdateWrapper<UserSubjectDO> eq1 = Wrappers.lambdaUpdate(UserSubjectDO.class).eq(UserSubjectDO::getDelFlag, 0).eq(UserSubjectDO::getUsername, reqDTO.getUsername()).set(UserSubjectDO::getDelFlag, 1);
            baseMapper.update(userSubjectDO, eq1);
            baseMapper.insert(one);
        } else {
            baseMapper.insert(one);
        }
        return true;
    }

    @Override
    public Long getUserSubject(String username) {
        UserSubjectDO userSubjectDO = baseMapper.selectOne(Wrappers.lambdaQuery(UserSubjectDO.class).eq(UserSubjectDO::getDelFlag, 0).eq(UserSubjectDO::getUsername, username));
        if (userSubjectDO == null) {
            return 0L;
        } else {
            return userSubjectDO.getSubjectId();
        }
    }

    @Override
    public Boolean isMySubject(String username, Long subjectId) {
        UserSubjectDO userSubjectDO = baseMapper.selectOne(Wrappers.lambdaQuery(UserSubjectDO.class).eq(UserSubjectDO::getUsername, username).eq(UserSubjectDO::getSubjectId, subjectId).eq(UserSubjectDO::getDelFlag, 0));
        if (userSubjectDO == null) {
            return false;
        } else {
            return true;
        }
    }
}
